package com.yupi.yuapidemo.controller.open;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.yupi.yuapicommon.model.common.BaseResponse;
import com.yupi.yuapicommon.model.common.BusinessException;
import com.yupi.yuapicommon.model.common.ErrorCode;
import com.yupi.yuapicommon.model.common.ResultUtils;
import com.zzsource.yuapicliensdk.model.params.OpenGenChartByAiParams;
import com.zzsource.yuapicliensdk.model.response.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.websocket.server.PathParam;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;

import static com.yupi.yuapidemo.utils.RequestUtils.buildUrl;

/**
 * @ClassName ServiceController
 * @Description TODO
 * @Author zzsource
 * @Date 2023/10/18 2:53
 * @Version 1.0
 **/
@RestController
@RequestMapping("/sdk")
@Slf4j
public class SdkServiceController {

    public static final String ACG_URL = "https://api.vvhan.com/api/acgimg";
    public static final String PoisonousChicken_URL = "https://www.iamwawa.cn/home/dujitang/ajax";
    public static final String RandomJoke_URL = "https://api.vvhan.com/api/joke";
    public static final String BIGenChart_URL = "http://localhost:8080/api/chart/open/gen";

    @GetMapping("/randomGen/joke")
    public BaseResponse<ResultResponse> getRandomJoke(@PathParam("type") String type) {
        String url = RandomJoke_URL;
        HashMap<String, String> queryMap = new HashMap<>();
        queryMap.put("type", type);
        String result = get(splicingRequest(url, queryMap));
        RandomJokeResponse randomJokeResponse = new RandomJokeResponse();
        if(StringUtils.isBlank(type)){
            randomJokeResponse.setJoke(result);
        } else if("json".equalsIgnoreCase(type)){
            JSONObject jsonObject = JSON.parseObject(result);
            randomJokeResponse.setJoke(jsonObject.getString("joke"));
            randomJokeResponse.setTitle(jsonObject.getString("title"));
        } else if("js".equalsIgnoreCase(type)){
            randomJokeResponse.setJs(result);
        }
        return ResultUtils.success(randomJokeResponse);
    }
    @GetMapping("/poisonousChickenSoup")
    public BaseResponse<ResultResponse> getPoisonousChickenSoup() {
        String result = get(PoisonousChicken_URL);
        JSONObject jsonObject = JSON.parseObject(result);
        String text = String.valueOf(jsonObject.get("data"));
        PoisonousChickenSoupResponse poisonousChickenSoupResponse = new PoisonousChickenSoupResponse();
        poisonousChickenSoupResponse.setText(text);
        return ResultUtils.success(poisonousChickenSoupResponse);
    }

    @GetMapping("/randomGen/ACGImg")
    public BaseResponse<ResultResponse> randmomGenACGImg(@PathParam("type") String type){
        if(!StringUtils.isBlank(type)){
            if("json".equalsIgnoreCase(type)){
                type = "?type=json";
            }else {
                throw new BusinessException(ErrorCode.PARAMS_ERROR);
            }
        }
        if(type == null){
            type = "?type=json";
        }
        String result = get(ACG_URL + type);
        JSONObject jsonObject = JSON.parseObject(result);
        ACGImgResponse acgImgResponse = new ACGImgResponse();
        acgImgResponse.setImgurl(String.valueOf(jsonObject.get("imgurl")));
        return ResultUtils.success(acgImgResponse);
    }

    @PostMapping("/bi/genChart")
    public BaseResponse<ResultResponse> gnChartByAI(@RequestBody OpenGenChartByAiParams openGenChartByAiParams, HttpServletRequest request){
        String result = null;
        try {
            result = HttpUtil.post(BIGenChart_URL, JSONUtil.toJsonStr(openGenChartByAiParams));
            JSONUtil.parseObj(result).getStr("data");
            BiResponse biResponse = Optional.ofNullable(result)
                    .map(r -> JSONUtil.parseObj(r).getStr("data"))
                    .filter(data -> StringUtils.isNotBlank(data))
                    .map(data -> JSONUtil.toBean(data, BiResponse.class))
                    .get();
            return ResultUtils.success(biResponse);
        }catch (Exception e){
            System.out.println(e);
        }

        return ResultUtils.error(ErrorCode.API_REQUEST_ERROR);
    }

    /**
     * get请求
     *
     * @param baseUrl 基本url
     * @param params  params
     * @return {@link String}
     * @throws Exception
     */
    public static <T> String get(String baseUrl, T params) throws Exception {
        return get(buildUrl(baseUrl, params));
    }

    /**
     * get请求
     *
     * @param url url
     * @return {@link String}
     */
    public static String get(String url) {
        String body = HttpRequest.get(url).execute().body();
        //log.info("【interface】：请求地址：{}，响应数据：{}", url, body);
        return body;
    }

    /**
     * 拼接URL请求
     *
     * @param url     路径
     * @return {@link String}
     */
    private  String splicingRequest(String url, Map<String, String> map) {
        StringBuilder urlBuilder = new StringBuilder(url);
        // urlBuilder最后是/结尾，去掉urlBuilder结尾的/
        if (urlBuilder.toString().startsWith("/")) {
            urlBuilder.setLength(urlBuilder.length() - 1);
        }
        if (!map.isEmpty()) {
            urlBuilder.append("?");
            for (Map.Entry<String, String> entry : map.entrySet()) {
                String key = entry.getKey();
                String value = entry.getValue();
                if(org.apache.commons.lang3.StringUtils.isAnyBlank(key, value))continue;
                urlBuilder.append(key).append("=").append(value).append("&");
            }
            urlBuilder.deleteCharAt(urlBuilder.length() - 1);
        }
        log.info("GET请求路径：{}", urlBuilder);
        return urlBuilder.toString();
    }
}
